<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/8/2
 * Time: 15:47
 */

namespace app\home\controller;


use think\Controller;
use think\Session;
class Common extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();
        //此处校验网站是否可以访问
        if(config("setting.site_on") != 1){
            die(config("setting.site_info"));
        }


        //不需登录可以访问的地址
        //地址路径全以小写
        $nologin_list = ["index.doforget", "index.login", "index.register", "index.forget", "index.treaty", 'index.getvcode', 'news.index', 'news.detail','paytype.sendsms'];
        $controller = request()->controller();
        $action = request()->action();
        $route = strtolower($controller.".".$action);
        if(!in_array($route, $nologin_list)){
            if(!session("user_id")){
                if(request()->isAjax()){
                    header("content-type:application/json");
                    exit(json_encode(["result_code"=>1111, "result_info"=>"用户未登录", "result_data"=>[]]));
                }else{
                    $this->redirect("Index/login");
                }
            }
        }
        $this->assign("route", $route);
        $this->templateTitle();
        //根据UId 发货用户信息
	    $uid = session("user_id");
	    $userinfo = array();
	    if($uid){
		    $userinfo = userallinfo($uid);
	    }
	    $this->assign("uinfo", $userinfo);
        
        //跳转页面是否有提示，如有显示提示
        if($tips = Session::pull("tips")){
            echo "<script>window.onload=function() {layer.alert('".$tips."');}</script>";
        }
       
    }

    /**
     * ajax成功信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxSuccess($info = "", $extra = array())
    {
        header("content-type:application/json");
        $result = array(
            "result_code" => 0,
            "result_info" => $info,
            "result_data" => $extra,
        );
        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * ajax失败信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxError($info = "", $extra = array())
    {
        header("content-type:application/json");
        $result = array(
            "result_code" => 2222,
            "result_info" => $info,
            "result_data" => $extra,
        );

        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 设置页面标题
     */
    protected function templateTitle($title='')
    {
        $this->assign("templateTitle", $title);
    }

    protected function currentUserId()
    {
        return \session('user_id');
    }

    /**
     * 当前用户
     * 一定是最新的数据 每次进入重新请求的
     * @return mixed
     */
    protected function currentUser()
    {
        //当前用户
        $user = db('user')->where('id', $this->currentUserId())->find();
        return $user;
    }

}